/**
 * @(#)HomeController.java
 * Description:
 * Version :	1.0
 * Copyright:	Copyright (c) 苗方清颜 版权所有
 */
package pub.lichao.test.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁测试类
 */
@Controller
public class DistributedLockController {
    @Autowired
    private RedissonClient redisson ;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(){
        return "/index";
    }

    @RequestMapping(value = "/occupyDistributedLock", method = RequestMethod.GET)
    public String occupyDistributedLock(RedirectAttributes redirectAttributes){
        RLock lock = null;
        try{
            //锁的key
            String key = "MF:DISTRIBUTEDLOCK:S:personId_1001";
            //获得分布式锁实例
            lock = redisson.getLock(key);
            //加锁并且设置自动失效时间15秒
            lock.lock(15, TimeUnit.SECONDS);
            //程序执行
            TimeUnit.SECONDS.sleep(10);
            //获取网络时间（多服务器测试统一时间）
            URL url=new URL("http://www.baidu.com");
            URLConnection conn=url.openConnection();
            conn.connect();
            long dateL=conn.getDate();
            Date date=new Date(dateL);
            //打印和返回结果
            System.out.println(date);
            redirectAttributes.addFlashAttribute("success",date);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            if (lock != null) lock.unlock();
        }

        return "redirect:/";
    }
}
